"""Authentication views."""

from django.conf import settings
from django.http import HttpResponseRedirect
from hcp.auth.core import REDIRECT_FIELD_NAME
from hcp.auth.forms import AuthenticationForm
from hcp.jinja import render_to_response
import hcp.auth.core

def login(request):
    redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            hcp.auth.core.login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            return HttpResponseRedirect(redirect_to)
    else:
        form = AuthenticationForm(request)
    request.session.set_test_cookie()
    return render_to_response('accounts/login.html', {
        'form': form,
        REDIRECT_FIELD_NAME: redirect_to,
    })

def logout(request):
    hcp.auth.core.logout(request)
    return render_to_response('accounts/logged_out.html')
